﻿/**************************************************************
 *
 * 唯一标识：be28a09b-52d3-4202-9f45-c4fc25eb41ab
 * 命名空间：Sgr.UPMS.Controllers
 * 创建时间：2023/8/27 20:32:39
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using MediatR;
using Microsoft.AspNetCore.Mvc;
using Sgr.AspNetCore.ActionFilters.AuditLogs;
using Sgr.AspNetCore.ActionFilters.Permissions;
using Sgr.UPMS.Application.Commands.Departments;
using Sgr.UPMS.Application.Queries;
using Sgr.UPMS.Application.ViewModels;

namespace Sgr.UPMS.Controllers
{
    /// <summary>
    /// 部门管理接口
    /// </summary>
    [Route("api/v1/sgr/departments")]
    [ApiController]
    [Produces("application/json")]
    [Tags("Department")]
    public class DepartmentController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IDepartmentQueries _departmentQueries;

        /// <summary>
        /// 初始化部门管理控制器
        /// </summary>
        public DepartmentController(IMediator mediator,
            IDepartmentQueries departmentQueries)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
            _departmentQueries = departmentQueries ?? throw new ArgumentNullException(nameof(departmentQueries));
        }

        #region Command

        /// <summary>
        /// 创建部门
        /// </summary>
        /// <param name="command">创建部门的请求参数</param>
        /// <remarks>
        /// 示例请求:
        ///
        ///     POST /api/v1/sgr/departments
        ///     {
        ///         "parentId": 1,
        ///         "name": "技术部",
        ///         "orderNumber": 1,
        ///         "remarks": "技术研发部门",
        ///         "leader": "张三",
        ///         "phone": "13800138000",
        ///         "email": "zhangsan@example.com",
        ///         "orgId": 1
        ///     }
        /// </remarks>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">创建成功</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.CreateDepartment)]
        [HttpPost]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [AuditLogActionFilter("创建部门")]
        public async Task<ActionResult<bool>> CreateAsync([FromBody] CreateDepartmentCommand command, System.Threading.CancellationToken cancellationToken)
        {
            return Ok(await _mediator.Send(command, cancellationToken));
        }

        /// <summary>
        /// 更新部门信息
        /// </summary>
        /// <param name="command">更新部门的请求参数</param>
        /// <remarks>
        /// 示例请求:
        ///
        ///     PUT /api/v1/sgr/departments
        ///     {
        ///         "departmentId": 1,
        ///         "name": "技术部",
        ///         "orderNumber": 1,
        ///         "remarks": "技术研发部门",
        ///         "leader": "张三",
        ///         "phone": "13800138000",
        ///         "email": "zhangsan@example.com"
        ///     }
        /// </remarks>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">更新成功</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.UpdateDepartment)]
        [HttpPut]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [AuditLogActionFilter("修改部门")]
        public async Task<ActionResult<bool>> UpdateAsync([FromBody] UpdateDepartmentCommand command, System.Threading.CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(command, cancellationToken);
            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="id">部门ID</param>
        /// <param name="isCascade">是否级联删除子部门，默认为true</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">删除成功</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.DeleteDepartment)]
        [HttpDelete("{id:long:min(1)}")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [AuditLogActionFilter("删除部门")]
        public async Task<ActionResult<bool>> DeleteAsync(
            [FromRoute] long id,
            [FromQuery] bool? isCascade = true,
            System.Threading.CancellationToken cancellationToken = default)
        {
            var result = await _mediator.Send(new DeleteDepartmentCommand { DepartmentId = id, IsCascade = isCascade ?? true }, cancellationToken);
            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }

        #endregion Command

        #region Queries

        /// <summary>
        /// 获取部门详情
        /// </summary>
        /// <param name="id">部门ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">获取成功</response>
        /// <response code="401">未经授权的访问</response>
        /// <response code="404">指定的部门不存在</response>
        [CheckPermission(Permissions.ViewDepartment)]
        [HttpGet("{id:long:min(1)}")]
        [ProducesResponseType(typeof(OutDepartmentViewModel), StatusCodes.Status200OK)]
        [AuditLogActionFilter("获取部门详情")]
        public async Task<ActionResult<OutDepartmentViewModel>> GetByIdAsync([FromRoute] long id, System.Threading.CancellationToken cancellationToken)
        {
            var result = await _departmentQueries.GetByIdAsync(id, cancellationToken);
            return result == null ? NotFound() : Ok(result);
        }

        /// <summary>
        /// 查询部门列表
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <remarks>
        /// 示例请求:
        ///
        ///     POST /api/v1/sgr/departments/search
        ///     {
        ///         "parentId": 1,
        ///         "orgId": 1
        ///     }
        /// </remarks>
        /// <response code="200">查询成功</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.ViewDepartment)]
        [HttpPost("search")]
        [ProducesResponseType(typeof(IEnumerable<OutDepartmentViewModel>), StatusCodes.Status200OK)]
        [AuditLogActionFilter("查询部门列表")]
        public async Task<ActionResult<IEnumerable<OutDepartmentViewModel>>> SearchAsync([FromBody] InDepartmentSearchModel request, System.Threading.CancellationToken cancellationToken)
        {
            return Ok(await _departmentQueries.GetListAsync(request, cancellationToken));
        }

        #endregion Queries
    }
}